package com.zyw.module.console.admin;

import com.zyw.module.console.admin.auth.QywxAuthService;
import com.zyw.module.console.admin.auth.SmsAuthService;
import com.zyw.module.console.sys.service.MenuService;
import com.zyw.module.console.sys.vo.MenuTreeVo;
import com.zyw.mvc.servlet.BaseController;
import com.zyw.mvc.support.WrappedResult;
import com.zyw.security.shiro.LoginFrom;
import com.zyw.security.shiro.web.authc.AuthInfo;
import com.zyw.security.shiro.web.session.SessionConfig;
import com.zyw.utils.PropertyHolder;
import com.zyw.utils.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhangyw
 * @date 2017/12/18 15:47
 */
@Controller
@RequestMapping("${path.auth.prefix}")
public class AuthController extends BaseController {
    private static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(AuthController.class);

    /**
     * 认证登录
     *
     * @return response
     */
    @RequestMapping(value = "login")
    @ResponseBody
    public WrappedResult _login(HttpServletRequest request, HttpServletResponse response) throws Exception {

        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {

            AuthInfo authInfo = null;

            Object principal = subject.getPrincipal();
            if (principal instanceof AuthInfo) {
                authInfo = (AuthInfo) principal;
            } else {
                throw new RuntimeException("principal can not instanceof AuthInfo, please check config");
            }

            Map<String, Object> tks = new HashMap<>(16);
            tks.put(SessionConfig.auth_tks_name, (String) subject.getSession().getId());
            tks.put("userid", authInfo.getUserid());
            tks.put("username", authInfo.getUsername());

            if (authInfo.isAnon()) {
                tks.put("newuser", true);
            }
            return wrappedSuccessResult(tks, "登录成功");
        } else {
            return wrappedFaliedResult((String) request.getAttribute("loginFailMsg"));
        }
    }

    /**
     * 验证是否有效访问
     *
     * @param tks 令牌
     * @return 401 未认证 ，1 允许访问
     */
    @RequestMapping(value = "vaild", method = RequestMethod.POST)
    @ResponseBody
    public WrappedResult _vaild(String tks) {

        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            return wrappedSuccessResult(null, "允许访问");
        }

        return wrappedFaliedResult(401, "会话超时");
    }

    @Autowired
    private SmsAuthService smsAuthService;
    @Autowired
    private QywxAuthService qywxAuthService;

    @RequestMapping(value = "sms", method = RequestMethod.POST)
    @ResponseBody
    public WrappedResult _sendLoginSmsCode(String phone) throws Exception {
        if (StringUtils.isEmpty(phone)) {
            return wrappedFaliedResult("请输入手机号");
        }
        smsAuthService.sendLoginSmsCode(phone);

        return wrappedSuccessResult(null, "发送成功");
    }


    @RequestMapping(value = "qrCode", method = RequestMethod.POST)
    @ResponseBody
    public WrappedResult qrCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //使用跳转页面的方式
        //https://open.work.weixin.qq.com/wwopen/sso/qrConnect?appid=ww100000a5f2191&agentid=1000000&redirect_uri=http%3A%2F%2Fwww.oa.com&state=web_login@gyoss9
        String status = qywxAuthService.genatorQywxStatus();
        StringBuilder url = new StringBuilder("");
        url.append("https://open.work.weixin.qq.com/wwopen/sso/qrConnect?");
        url.append("appid=").append(PropertyHolder.getString("qywx.appid")).append("&");
        url.append("agentid=").append(PropertyHolder.getString("qywx.agentid")).append("&");
        url.append("state=").append(status).append("&");
        url.append("redirect_uri=");

        String rs = PropertyHolder.getString("qywx.redirect_uri") + "?lf=" + LoginFrom.qywx.name();
        String redirect = request.getParameter("redirect");
        if (StringUtils.isNotEmpty(redirect) && !"/".equals(redirect)) {
            rs = rs + "&redirect=" + redirect;
        }

        url.append(URLEncoder.encode(rs));


        logger.debug("请求企业微信二维码链接:{}", url);
        return wrappedSuccessResult(url.toString(), "二维码生成成功!");

    }

    /**
     * 登出
     *
     * @param tks
     * @return
     */
    @RequestMapping(value = "logout", method = RequestMethod.POST)
    @ResponseBody
    public WrappedResult _logout(String tks) {

        Subject subject = SecurityUtils.getSubject();
        subject.logout();

        return wrappedSuccessResult("", "登出成功");
    }

    @Autowired
    private MenuService menuService;

    /**
     * 根据登录的用户，拉取菜单
     *
     * @return
     */
    @RequestMapping("menu")
    @ResponseBody
    public WrappedResult loadMenu(@RequestParam(defaultValue = "1") Integer sysid) {
        List<MenuTreeVo> menus = menuService.getMenuTreeList(sysid);
        return wrappedSuccessResult(menus);
    }
}
